// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, ipcRenderer, dialog } = require('electron')
const path = require('path')
const MusicDataStore = require('./MusicDataStore')

const store = new MusicDataStore({ 'name': 'MusicData' })

class AppWindow extends BrowserWindow {
  constructor(config, fileLocation) {
    const basicConfig = {
      width: 800,
      height: 600,
      show: false,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
      }
    }
    const finalConfig = { ...basicConfig, ...config }
    super(finalConfig)
    this.loadFile(fileLocation)
    this.once('ready-to-show', () => {
      this.show()
    })
  }
}

app.on('ready', () => {
  const mainWindow = new AppWindow({}, './renderer/index.html')
  mainWindow.webContents.on('did-finish-load',() =>{
    mainWindow.send('getTracks',store.getTracks())
  })
  // mainWindow.openDevTools()
  ipcMain.on('add-music', () => {
    const addMusicWinow = new AppWindow({
      width: 500,
      height: 400,
      parent: mainWindow
    }, './renderer/add.html')
    // addMusicWinow.openDevTools()
  })


  ipcMain.on('open-music-file', (event) => {
    dialog.showOpenDialog({
      properties: ['openFile', 'multiSelections'],
      filters: [
        { name: 'Music', extensions: ['mp3'] }
      ]
    }).then(files => {
      event.sender.send('selected-file', files)
    })
  })

  ipcMain.on('add-tracks', (event, tracks) => {
    const updatedTracks = store.addTracks(tracks).getTracks()
    mainWindow.send('getTracks',updatedTracks)
  })

  ipcMain.on('delete-track', (event, id) => {
    const updatedTracks = store.deleteTracks(id)
    mainWindow.send('getTracks',store.getTracks())
  })
})
